﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using BOSS.Domain.Security;
using BOSS.Framework;
using BOSS.Service.Security;

namespace BOSS.Web.Controllers
{

    [HandleError]
    public class AccountController : AbstractController
    {
        /// <summary>
        /// 获取 / 设置 安全服务
        /// </summary>
        public ISecurityService SecurityService { get; set; }

        /// <summary>
        /// 新增或修改员工账户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Create(int? id)
        {
            Account account = new Account();
            if (id != null)
            {
                account = this.AccountService.FindById(id.Value);
            }

            if (this.Request.IsPost())
            {
                TryUpdateModel(account, new[] { "LoginName", "EmployeeId", "FullName", "IdentityCard", "Telephone", "Mobile", "Email", "QQ", "MSN", "StartingDate" });

                Account compare = this.AccountService.FindByEmployeeId(account.EmployeeId);
                if (compare != null && compare != account)
                {
                    ModelState.AddModelError("EmployeeId", "该工号已经存在.");
                }
                compare = this.AccountService.FindByLoginName(account.LoginName);
                if (compare != null && compare != account)
                {
                    ModelState.AddModelError("LoginName", "该登录名已经存在.");
                }
                if (string.IsNullOrEmpty(account.FullName))
                {
                    ModelState.AddModelError("FullName", "姓名不能为空.");
                }
                if (string.IsNullOrEmpty(account.Telephone) && string.IsNullOrEmpty(account.Mobile))
                {
                    ModelState.AddModelError("Telephone", "电话和手机至少要填写一个.");
                    ModelState.AddModelError("Mobile", "电话和手机至少要填写一个.");
                }
                if (account.StartingDate == DateTime.MinValue)
                {
                    ModelState.AddModelError("StartingDate", "请选择入职日期.");
                }

                if (ModelState.IsValid)
                {
                    this.AccountService.SaveOrUpdate(account);

                    return View("Details", account);
                }
            }

            return View(account);
        }

        /// <summary>
        /// 员工详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                throw new LogicalException("员工账户 Id 为空.");
            }

            Account account = this.AccountService.FindById(id.Value);
            if (account == null)
            {
                throw new LogicalException(string.Format("未能找到 Id 为 {0} 的员工账户.", id));
            }

            return View(account);
        }

        /// <summary>
        /// 搜索员工
        /// </summary>
        /// <param name="start"></param>
        /// <param name="limit"></param>
        /// <param name="sort"></param>
        /// <param name="dir"></param>
        /// <returns></returns>
        public ActionResult Search(int? start, int? limit, string sort, string dir)
        {
            if (this.Request.IsPost())
            {
                return base.ShowSearchResult("SearchResult", "Account", start, limit, sort, dir);
            }

            return View();
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="loginName"></param>
        /// <param name="password"></param>
        /// <param name="verifyCode"></param>
        /// <param name="returnUrl"></param>
        /// <returns></returns>
        public ActionResult Login(string loginName, string password, string verifyCode, string returnUrl)
        {
            string host = RequestUrlHelper.GetHost(this.Request);


            LoginInfo loginInfo = null;
            if (this.Request.IsAuthenticated)
            {
                loginInfo = this.SecurityService.GetLoginInfo(true);
                if (loginInfo != null)
                {
                    global::System.Web.HttpContext.Current.Response.Redirect(Url.Action("Index", "Home"), true);
                }
            }

            if (this.Request.IsPost())
            {
#if DEBUG
                this.Session[VerifyImageCreator.DEFAULT_VERIFY_CODE_KEY] = verifyCode = "NOT_REQUIRED";
#endif

                ModelState.SetModelValue("VerifyCode", new ValueProviderResult(string.Empty, string.Empty, null));

                if (loginName != null)
                {
                    loginName = loginName.Trim();
                    ViewData["LoginName"] = loginName;
                }
                if (string.IsNullOrEmpty(loginName))
                {
                    ModelState.AddModelError("LoginName", "请输入登录名。");
                }
                if (string.IsNullOrEmpty(password))
                {
                    ModelState.AddModelError("Password", "请输入密码。");
                }
                if (string.IsNullOrEmpty(verifyCode))
                {
                    ModelState.AddModelError("VerifyCode", "请输入验证码。");
                }

                if (ModelState.IsValid)
                {
                    string storedVerifyCode = (string)this.Session[VerifyImageCreator.DEFAULT_VERIFY_CODE_KEY];
                    if (!string.Equals(verifyCode, storedVerifyCode, StringComparison.OrdinalIgnoreCase))
                    {
                        ModelState.AddModelError("VerifyCode", "验证码输入错误。");
                    }
                    else
                    {
                        loginInfo = this.SecurityService.TryLogin(loginName, password, this.Request.UserHostAddress);
                        if (loginInfo == null)
                        {
                            ModelState.AddModelError("Password", "登录名或密码错。");
                        }
                    }
                }
            }

            if (loginInfo != null)
            {
                string returnValue = this.SecurityService.DoLogin(loginInfo);

                if (!string.IsNullOrEmpty(returnValue))
                {
                    global::System.Web.HttpContext.Current.Response.Redirect(Url.Action("Index", "Home"), true);
                }
            }

            Account account = new Account() { LoginName = loginName };

            return View("Login", account);
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public ActionResult Logout()
        {
            this.SecurityService.Logout();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult ChangePassword(int? id, string oldPassword, string newPassword, string confirmPassword)
        {
            if (id == null)
            {
                throw new LogicalException("账户 Id 为空.");
            }

            Account account = this.AccountService.FindById(id.Value);
            if (this.Request.IsPost())
            {
                if (string.IsNullOrEmpty(oldPassword))
                {
                    ModelState.AddModelError("OldPassword", "请填写旧密码.");
                }
                else
                {
                    if (!PasswordCryptor.Default.Encrypt(oldPassword).Equals(account.Password))
                    {
                        ModelState.AddModelError("OldPassword", "密码错误.");
                    }
                }
                if (string.IsNullOrEmpty(newPassword))
                {
                    ModelState.AddModelError("NewPassword", "请填写新密码.");
                }
                if (string.IsNullOrEmpty(confirmPassword))
                {
                    ModelState.AddModelError("ConfirmPassword", "请重复填写新密码.");
                }

                if (newPassword != confirmPassword)
                {
                    ModelState.AddModelError("ConfirmPassword", "新密码不一致.");   
                }

                if (ModelState.IsValid)
                {
                    account.Password = PasswordCryptor.Default.Encrypt(confirmPassword);
                    this.AccountService.SaveOrUpdate(account);

                    return View("CloseModalDialog");
                }
            }

            return View(account);
        }
    }
}
